/**
 * This file is used specifically for security reasons.
 * Here you can access Nodejs stuff and inject functionality into
 * the renderer thread (accessible there through the "window" object)
 *
 * WARNING!
 * If you import anything from node_modules, then make sure that the package is specified
 * in package.json > dependencies and NOT in devDependencies
 *
 * Example (injects window.myAPI.doAThing() into renderer thread):
 *
 *   import { contextBridge } from 'electron'
 *
 *   contextBridge.exposeInMainWorld('myAPI', {
 *     doAThing: () => {}
 *   })
 *
 * WARNING!
 * If accessing Node functionality (like importing @electron/remote) then in your
 * electron-main.ts you will need to set the following when you instantiate BrowserWindow:
 *
 * mainWindow = new BrowserWindow({
 *   // ...
 *   webPreferences: {
 *     // ...
 *     sandbox: false // <-- to be able to import @electron/remote in preload script
 *   }
 * }
 */

import { contextBridge, ipcRenderer } from 'electron'
const { execSync, exec } = require('node:child_process')
const fs = require('fs')

contextBridge.exposeInMainWorld('NAS', {
  exec: (str: string, callback: (type: string, data: string) => void) => {
    const child = exec(str)
    // 监听标准输出，获取日志信息
    child.stdout.on('data', (data: string) => {
      callback('progress', data)
    })

    // 监听标准错误输出，获取错误信息
    child.stderr.on('data', (data: string) => {
      callback('error', data)
    })

    // 监听命令执行完成事件
    child.on('close', (code: string) => {
      callback('close', code)
    })
  },

  execSync: async (str: string) => {
    const output = await execSync(str)
    // console.log(output.toString())
    return output.toString()
  },

  // 文件系统
  chooseFolder: () => {
    return ipcRenderer.invoke('chooseFolder')
  },
  openFile: () => {
    return ipcRenderer.invoke('openFile')
  },
  openDirectory: (path: string) => {
    ipcRenderer.send('openDirectory', path)
  },
  fileExists: (path: string) => {
    try {
      if (fs.existsSync(path)) {
        console.log(`文件存在: ${path}`)
        return true
      } else {
        console.log(`文件不存在: ${path}`)
        return false
      }
    } catch (err) {
      console.error(`检查文件是否存在时出错: ${err}`)
      return false
    }
  },
})
